package cn.main.service.impl;

import cn.main.core.SessionKey;
import cn.main.core.UserSession;
import cn.main.dao.DomainDao;
import cn.main.entity.sys.Role;
import cn.main.entity.sys.SysColumn;
import cn.main.entity.sys.SysFunction;
import cn.main.entity.sys.User;
import cn.main.service.SessionUserService;
import cn.main.utils.DES;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Author: chengwei
 * Date:   2016/7/14
 * Time:   14:33
 */
@Service
public class SessionUserServiceImpl implements SessionUserService {

    @Resource
    private DomainDao dao;
    
    @Override
    public boolean doLogin(HttpServletRequest req, String username, String password, String checkCode) {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return false;
        }
        Map<String,Object> map = dao.queryForMap("select * from sys_user where username = ?",username);
        boolean b =  map.size() >0 && DES.getMD5(password,username).equals(map.get("password"));
        if (b) {
            UserSession session = new UserSession();
            User user = dao.getDomain(String.valueOf(map.get("user_id")),User.class);
            session.setUser(user);
            List<?> a = dao.getCurrentSession().createSQLQuery("SELECT r.* FROM sys_role r INNER JOIN sys_user_role ur ON r.role_id = ur.role_id WHERE ur.user_id = :user_id")
                    .addEntity("r", Role.class)
                    .setString("user_id",user.getUserId()).list();
            
            Set<Role> roleSet = new HashSet<>();
            for (Object o : a) {
                if (o instanceof Role) {
                    Role role = (Role) o;
                    role = dao.getDomain(role.getRoleId(),Role.class);
                    roleSet.add(role);
                }
            }
            
            List<SysFunction> functions = dao.getDomains(SysFunction.class,"where aPublic = 1");
            Set<SysFunction> functionSet = new HashSet<>();
            functionSet.addAll(functions);
            session.setRoles(roleSet);
            session.setFunctions(functionSet);
            req.getSession().setAttribute(SessionKey.SESSION_KEY,session);
        }
        return b;
    }
}
